<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Fenxiao_Product extends Stourweb_Controller
{
    private $_level_num=3;
    public function before()
    {
        $level_num = Model_Fenxiao_Config::get_val('cfg_fenxiao_level_num');
        $this->_level_num=empty($level_num)?3:$level_num;
        $this->assign('level_num',$level_num);
        parent::before();
    }

    /*
   产品列表
    */
    public function action_list()
    {
        $action = $this->params['action'];
        $typeid = $this->params['typeid'];
        $groupid = $this->params['groupid'];
        $typeid = empty($typeid)?$_GET['typeid']:$typeid;
        $groupid = empty($groupid)?$_GET['groupid']:$groupid;
        $groupid = empty($groupid)?0:$groupid;
        $commissiontype = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$typeid,$groupid);
        $commissiontype = empty($commissiontype)?0:$commissiontype;
        if (empty($action))  //显示线路列表页
        {
            $this->assign('typeid',$typeid);
            $this->assign('groupid',$groupid);
          //  $products=Model_Fenxiao::get_fenxiao_product();
           // $this->assign('products',$products);
            if($typeid==1)
            {
                $people_group = Model_Sysconfig::get_people_group();
                $this->assign('people_group',$people_group);
            }
            $this->assign('commissiontype',$commissiontype);
            $this->display('admin/fenxiao/product/list');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $order = 'order by a.modtime desc,a.addtime desc';
            $webid = empty($webid) ? -1 : $webid;
            $keyword = Common::getKeyword($keyword);
            $table= $this->get_table($typeid);
            $ftable='sline_'.$table;

            $fields='a.title,a.webid,a.id,a.aid,a.modtime,b.fxratio,b.fxratio1,b.fxratio2,b.fxratio3,b.pm_fxratio,b.pm_fxratio1,b.pm_fxratio2,b.pm_fxratio3,b.cash,b.cash1,b.cash2,b.cash3,b.cash_old,b.cash_child,b.cash1_old,b.cash1_child,b.cash2_old,b.cash2_child,cash3_old,cash3_child,b.displayorder';
            $fields.=',b.cash_people4,b.cash1_people4,b.cash2_people4,b.cash3_people4,b.cash_people5,b.cash1_people5,b.cash2_people5,b.cash3_people5,b.cash_people6,b.cash1_people6,b.cash2_people6,b.cash3_people6';
            if(empty($table))
            {
                return;
            }
            if ($sort[0]['property'])
            {
                $property=$sort[0]['property'];
                $ratioFields=array('fxratio1','fxratio2','fxratio3','fxratio','cash1','cash2','cash3','cash','pm_fxratio','pm_fxratio1','pm_fxratio2','pm_fxratio3');
                if(in_array($property,$ratioFields))
                {
                    $orderStr = "b.{$property} {$sort[0]['direction']}";
                }

                if($property=='displayorder')
                {
                    $orderStr = " ifnull(b.displayorder, 999999) {$sort[0]['direction']} ";
                }

                if($property=='modtime')
                {
                    $orderStr = "a.modtime {$sort[0]['direction']}";
                }
                if(!empty($orderStr))
                {
                    $order=" order by {$orderStr},a.modtime desc,a.addtime desc";
                }
            }
            $w = "where a.id is not null and a.ishidden=0 ";
            $w.= $table=='model_archive'?" and a.typeid={$typeid} ":"";
            $w .= !empty($keyword)? " and (a.id='{$keyword}' or a.title like '%{$keyword}%')":'';


            $sql = "select {$fields} from {$ftable} a left join sline_fenxiao_ratio b on a.id=b.productid and b.typeid={$typeid} and b.groupid='{$groupid}'  $w $order limit  $start,$limit";

            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from {$ftable} a $w")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as $k=>&$v)
            {
               $v['url']=$this->get_url($typeid,$v['webid'],$v['aid'],$v['id']);
               $v['modtime'] = empty($v['modtime'])?'':date('Y-m-d',$v['modtime']);
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {

        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {
            $id = $_POST['id'];
            $field = $_POST['field'];
            $val = $_POST['val'];

            if($field=='displayorder')
            {
                $val = empty($val)?'999999':$val;
            }
            $typeid = $_POST['typeid'];
            $groupid = $_POST['groupid'];
            $groupid = empty($groupid)?0:$groupid;
            if(empty($id) || empty($typeid))
            {
                echo 'no';
                return;
            }
            $curtime=time();
            $ratioModel=ORM::factory('fenxiao_ratio')->where('typeid','=',$typeid)->and_where('productid','=',$id)->and_where('groupid','=',$groupid)->find();
            $ratioModel->typeid=$typeid;
            $ratioModel->productid=$id;
            $ratioModel->$field=abs($val);
            $ratioModel->modtime=$curtime;
            $ratioModel->groupid=$groupid;
            $ratioModel->save();
            echo 'ok';
        }
        else if($action=='updatesome')
        {
            $id = $_POST['id'];
            $typeid = $_POST['typeid'];
            $groupid = $_POST['groupid'];
            $groupid = empty($groupid)?0:$groupid;


            if(empty($id) || empty($typeid))
            {
                echo 'no';
                return;
            }
            /*
             * cash1_child: 1
cash1: 2
cash1_old: 3
cash1_people4: 4
cash1_people5: 5
cash1_people6: 6
cash2_child: 7
cash2: 8
cash2_old: 9
cash2_people4: 10
cash2_people5: 11
cash2_people6: 12
cash3_child: 13
cash3: 14
cash3_old: 15
cash3_people4: 16
cash3_people5: 17
cash3_people6: 18
cash_child: 19
cash: 20
cash_old: 21
cash_people4: 22
cash_people5: 23
cash_people6: 24
             */






            $curtime=time();
            $ratioModel=ORM::factory('fenxiao_ratio')->where('typeid','=',$typeid)->and_where('productid','=',$id)->find();
            $ratioModel->typeid=$typeid;
            $ratioModel->productid=$id;
            $ratioModel->groupid = $groupid;

            foreach($_POST as $k=>$v)
            {
                if(strpos($k,'cash')!==FALSE || strpos($k,'fxratio')!==FALSE)
                {
                    $ratioModel->$k = $v;
                }

            }

            $ratioModel->modtime=$curtime;
            $ratioModel->save();
            echo 'ok';
        }
    }
    //分组列表
    public function action_group()
    {
        $action=$this->params['action'];
        if(empty($action))
        {
            $this->display('admin/fenxiao/product/group');
        }
        else if($action=='read')
        {
            $list=ORM::factory('fenxiao_group')->get_all();
            array_unshift($list,array('id'=>0,'title'=>'默认分组','description'=>'所有未设置分组的分销商都属于默认分组'));
            foreach($list as $k=>&$v)
            {
                $v['membernum']= ORM::factory('fenxiao')->where('fxgroupid','=',$v['id'])->count_all();
            }
            $result['total'] = count($list);
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
    }

    //全局设置分佣
    public function action_reward()
    {
        $productlist=Model_Fenxiao::get_fenxiao_product();
        $groupid = $_GET['groupid'];
        $groupid = empty($groupid)?0:$groupid;
        $group_name = DB::select('title')->from('fenxiao_group')->where('id','=',$groupid)->execute()->get('title');
        $group_name = empty($groupid)?'默认分组':$group_name;
        $list=DB::select()->from('fenxiao_config')->where('groupid','=',$groupid)->or_where('varname','like','cfg_fenxiao_product_displayorder_%')->execute()->as_array();
        $info=array();
        foreach($list as $v)
        {
            $info[$v['varname']]=$v['value'];
        }
        $this->assign('info',$info);
        $this->assign('productlist',$productlist);
        $this->assign('group_name',$group_name);
        $this->assign('groupid',$groupid);
        $this->display('admin/fenxiao/product/reward');
    }

    //保存全局分佣
    public function action_ajax_reward_save()
    {
        $groupid = $_POST['groupid'];
        $groupid = empty($groupid)?0:$groupid;
        foreach($_POST as $k=>$v)
        {
            if(strpos($k,'cfg_')!==false)
            {
                $real_groupid = $groupid;
                if(strpos($k,'cfg_fenxiao_product_displayorder_')!==false)
                {
                    $real_groupid = 0;
                }
                $model=ORM::factory('fenxiao_config')->where('varname','=',$k)->and_where('groupid','=',$real_groupid)->find();
                $model->varname=$k;
                $model->value=$v;
                $model->groupid = $real_groupid;
                $model->save();
            }
        }
        echo json_encode(array('status'=>true,'msg'=>'保存成功'));
    }


    //获取表名
    private function get_table($typeid)
    {
        $model=ORM::factory('model',$typeid);
        if(!$model->loaded())
            return false;
        return $model->maintable;
    }
    //获取产品URL
    private function get_url($typeid,$webid,$aid,$id)
    {
        $model=ORM::factory('model',$typeid);
        if(!$model->loaded())
            return false;
        $webid=empty($webid)?0:$webid;
        $realid=$typeid==101?$id:$aid;
        $urlFolder=empty($model->correct)?$model->pinyin:$model->correct;
        $url=Common::getBaseUrl($webid).'/'.$urlFolder.'/show_'.$realid.'.html';

        return $url;
    }

    public function action_info()
    {
        $action = $this->params['action'];
        $typeid = $this->params['typeid'];
        $typeid = empty($typeid)?$_GET['typeid']:$typeid;

        if (empty($action))  //显示线路列表页
        {
            $productlist=Model_Fenxiao::get_fenxiao_product();
            $this->assign('typeid',$typeid);
            $this->assign('productlist',$productlist);
            $this->display('admin/fenxiao/product/info');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $order = 'order by a.modtime desc,a.addtime desc';
            $webid = empty($webid) ? -1 : $webid;
            $keyword = Common::getKeyword($keyword);
            $table= $this->get_table($typeid);
            $ftable='sline_'.$table;

            $fields='a.title,a.webid,a.id,a.aid,a.modtime,b.litpic';
            if(empty($table))
            {
                return;
            }
            if ($sort[0]['property'])
            {
                if(!empty($orderStr))
                {
                    $order=" order by {$orderStr},a.modtime desc,a.addtime desc";
                }

                if($sort[0]['property']=='litpic')
                {
                    $order=" order by case when b.litpic='' or b.litpic is null then 0 else 1 end ". $sort[0]['direction'];
                }
            }
            $w = "where a.id is not null and a.ishidden=0 ";
            $w.= $table=='model_archive'?" and a.typeid={$typeid} ":"";
            $w .= !empty($keyword)? " and (a.id='{$keyword}' or a.title like '%{$keyword}%')":'';

            $sql = "select {$fields} from {$ftable} a left join sline_fenxiao_product b on a.id=b.productid and b.typeid={$typeid}  $w $order limit  $start,$limit";
            $totalcount_arr = DB::query(Database::SELECT, "select count(*) as num from {$ftable} a $w")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as $k=>&$v)
            {
                $v['url']=$this->get_url($typeid,$v['webid'],$v['aid'],$v['id']);
                $v['modtime'] = empty($v['modtime'])?'':date('Y-m-d',$v['modtime']);
                $v['typeid'] = $typeid;
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {

        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {
            $id = $_POST['id'];
            $field = $_POST['field'];
            $val = $_POST['val'];
            $typeid = $_POST['typeid'];

           $product_model = ORM::factory('fenxiao_product')->where('typeid','=',$typeid)->and_where('productid','=',$id)->find();
           $product_model->typeid = $typeid;
            $product_model->productid = $id;
            $product_model->$field = $val;
            $product_model->save();
            echo 'ok';
        }
    }

    //对话框图片
    public function action_dialog_pic()
    {

        $typeid = $this->params['typeid'];
        $id = $this->params['id'];
        $info = DB::select()->from('fenxiao_product')->where('typeid','=',$typeid)->and_where('productid','=',$id)->execute()->current();
        $info['productid'] = $id;
        $info['typeid'] = $typeid;
        $this->assign('info',$info);
        $this->display('admin/fenxiao/product/dialog_pic');
    }
}